<template>
  <div style="margin: 15px">
    <div>
      <el-button
        @click="dialogTableVisible = true"
        icon="el-icon-upload2"
        type="primary"
        >导入excel</el-button
      >
      <el-button
        icon="el-icon-download"
        type="primary"
        @click="handleExportDicts"
        >导出excel</el-button
      >
    </div>

    <div style="margin-top: 20px">
      <el-table
        :data="levelOneDicts"
        style="width: 100%"
        row-key="id"
        border
        lazy
        :load="load"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
        <el-table-column prop="name" label="标题"> </el-table-column>
        <el-table-column prop="value" label="值"> </el-table-column>
        <el-table-column prop="dictCode" label="编码"> </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="mini" @click="handleEdit(scope.row)"
              >编辑</el-button
            >
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.row)"
              >删除</el-button
            >
            <el-button size="mini" type="danger" @click="handleAdd(scope.row)"
              >新增</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 新增数据字典对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="addDictdialogFormVisible"
      :close-on-click-modal="false"
    >
      <el-form>
        <el-form-item label="标题" :label-width="formLabelWidth">
          <el-input v-model="dict.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="值" :label-width="formLabelWidth">
          <el-input-number
            v-model="dict.value"
            :min="1"
            :max="100"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="编码" :label-width="formLabelWidth">
          <el-input v-model="dict.dictCode" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addDictdialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmitDict">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 上传组件的对话框：点击导入按钮时显示 -->
    <el-dialog title="导入数据字典" :visible.sync="dialogTableVisible">
      <!-- 
          action:上传的服务器地址
          limit: 上传文件的限制个数
          on-success:上传成功的回调
          name: 上传组件上传文件的名称
       -->
      <el-upload
        ref="upload"
        class="upload-demo"
        :action="uploadUrl"
        :on-success="handleUploadSuccess"
        :on-error="handlerUploadError"
        name="excel"
        :limit="1"
      >
        <el-button size="small" type="primary">点击上传</el-button>
        <div slot="tip" class="el-upload__tip">只能上传xls/xlsx/csv文件</div>
      </el-upload>
    </el-dialog>
  </div>
</template>
<script>
/**
 * 数据列表中，一个json的hasChildren为true表示有下一级，页面会展示展开图表
 * 展示数据列表的table，load属性绑定的函数就是展开事件函数，会将一组数据解析展示到当前行的下一级
 * 后端需要实现的接口
 *
 * 根据父id查询下一级数据字典，每个一级字典需要设置hasChildren属性和值
 */
import dictApi from "@/api/dict";
export default {
  data() {
    return {
      formLabelWidth: "120px",
      dict: {},
      addDictdialogFormVisible: false,
      title: "新增数据字典",
      uploadUrl: "http://192.168.1.170/admin/core/dict/import",
      dialogTableVisible: false,
      //一级数据字典：
      levelOneDicts: [],
    };
  },
  created() {
    //异步加载一级数据字典
    dictApi.getByParentId("1").then((r) => {
      this.levelOneDicts = r.data.items;
    });
  },
  methods: {
    //新增数据字典提交按钮事件函数
    handleSubmitDict() {
      dictApi.save(this.dict).then((r) => {
        // this.$message()
        //刷新当前页面
        window.location.reload();
      });
    },
    handleAdd(dict) {
      //接收点击按钮所在行的数据字典的id当做新增数据字典的父id
      this.dict.parentId = dict.id;
      //弹出新增对话框
      this.addDictdialogFormVisible = true;
    },
    //操作按钮组的事件函数
    handleEdit(dict) {
      console.log(dict);
    },
    //提交删除请求，删除数据字典
    handleDelete(dict) {
      this.$confirm(`此操作将删除数据字典【${dict.name}】, 是否继续?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          dictApi.deleteById(dict.id).then((r) => {
            this.$message.success("删除成功");
            //重新加载当前页面
            window.location.reload();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    //加载函数：点击页面中的展开图表触发
    load(tree, treeNode, resolve) {
      // console.log(tree, treeNode);
      //tree表示点击行的json对象：可以获取到id
      dictApi.getByParentId(tree.id).then((r) => {
        //异步请求查询数据集合设置到resolve函数中就可以解析展示到下一级
        resolve(r.data.items);
      });
    },

    //导出数据字典单击事件函数
    handleExportDicts() {
      window.location = "http://192.168.1.170/admin/core/dict/export";
    },
    //响应报文状态码为200时回调
    handleUploadSuccess(response, file, fileList) {
      console.log(response);
      if (response.code === 0) {
        //r对象的code值代表成功执行
        //弹出提示关闭对话框
        this.$message.success(response.msg);
      } else {
        //r对象code值代表失败时执行
        this.$message.error(response.msg);
      }

      this.dialogTableVisible = false;
      //清除对话框中的上传组件的缓存
      //this.$refs.upload  获取vue对象渲染的范围内所有有ref值的标签集合，根据ref值获取指定的那个标签
      this.$refs.upload.clearFiles();
    },
    //响应报文状态码不是200时回调
    handlerUploadError(err, file, fileList) {
      console.log(err);
      this.$message.error("上传失败");
      this.dialogTableVisible = false;
      this.$refs.upload.clearFiles();
    },
  },
};
</script>
